import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import os
import random

# ===== 全局中文字体设置（适用于 macOS） =====
matplotlib.rcParams['font.sans-serif'] = ['PingFang SC', 'STHeiti', 'Arial Unicode MS']
matplotlib.rcParams['axes.unicode_minus'] = False  # 解决坐标轴负号显示问题

def roll_fair_dice(n_rolls=10, n_experiments=10000, filename="dice_fair.txt"):
    """
    公平骰子：每次掷骰子独立均匀 [1,6]
    """
    rolls = np.random.randint(1, 7, size=(n_experiments, n_rolls))
    sums = rolls.sum(axis=1)

    with open(filename, "w", encoding="utf-8") as f:
        for s in sums:
            f.write(str(s) + "\n")

    print(f"✅ 公平骰子结果已保存到 {filename}")
    return filename

def roll_biased_dice(n_rolls=10, n_experiments=10000, filename="dice_biased.txt"):
    """
    有问题的骰子：下一次更大概率比上一次大
    规则：
      - 第一次均匀 [1,6]
      - 之后：80% 的概率在 [prev, 6] 中抽，20% 的概率在 [1, prev] 中抽
    """
    sums = []
    for _ in range(n_experiments):
        seq = []
        # 第一个数均匀分布
        prev = random.randint(1, 6)
        seq.append(prev)
        for _ in range(n_rolls - 1):
            if random.random() < 0.8:
                # 倾向更大
                next_val = random.randint(prev, 6)
            else:
                next_val = random.randint(1, prev)
            seq.append(next_val)
            prev = next_val
        sums.append(sum(seq))

    with open(filename, "w", encoding="utf-8") as f:
        for s in sums:
            f.write(str(s) + "\n")

    print(f"✅ 有问题骰子结果已保存到 {filename}")
    return filename

def load_data(filename):
    """
    从文件读取点数和
    """
    with open(filename, "r", encoding="utf-8") as f:
        sums = [int(line.strip()) for line in f if line.strip()]
    return sums

def save_distribution(sums, n_rolls=10, output_file="dice_distribution.pdf", title="骰子点数和的分布"):
    """
    绘制并保存直方图（纵轴为次数）
    """
    plt.figure(figsize=(10, 6))
    plt.hist(
        sums,
        bins=range(min(sums), max(sums) + 2),
        density=False,
        rwidth=0.8,
        color='skyblue',
        edgecolor='black'
    )
    plt.title(f"{title}（掷 {n_rolls} 次）")
    plt.xlabel("点数和")
    plt.ylabel("次数")
    plt.grid(axis="y", linestyle="--", alpha=0.7)

    plt.savefig(output_file, format="pdf", bbox_inches="tight")
    plt.close()
    print(f"📂 图表已保存为 {output_file}")

if __name__ == "__main__":
    n_rolls = 50
    n_experiments = 200000

    # 公平骰子
    fair_file = "dice_fair.txt"
    fair_pdf = "dice_fair.pdf"
    roll_fair_dice(n_rolls=n_rolls, n_experiments=n_experiments, filename=fair_file)
    fair_sums = load_data(fair_file)
    save_distribution(fair_sums, n_rolls, output_file=fair_pdf, title="公平骰子点数和的分布")

    # 有问题骰子
    biased_file = "dice_biased.txt"
    biased_pdf = "dice_biased.pdf"
    roll_biased_dice(n_rolls=n_rolls, n_experiments=n_experiments, filename=biased_file)
    biased_sums = load_data(biased_file)
    save_distribution(biased_sums, n_rolls, output_file=biased_pdf, title="有问题骰子点数和的分布")